package com.jinsilu.freight.ui.activity;

import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.blankj.utilcode.util.LogUtils;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.hjq.base.BaseDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.exception.ResultException;
import com.hjq.http.listener.HttpCallback;
import com.jinsilu.freight.R;
import com.jinsilu.freight.aop.SingleClick;
import com.jinsilu.freight.common.MyActivity;
import com.jinsilu.freight.helper.CommonHelper;
import com.jinsilu.freight.http.model.HttpData;
import com.jinsilu.freight.http.model.HttpListData;
import com.jinsilu.freight.http.request.BlankNoteConsumptionApi;
import com.jinsilu.freight.http.request.BlankNoteRemainApi;
import com.jinsilu.freight.http.request.GetBlankNoteListApi;
import com.jinsilu.freight.http.response.RecordWhiteNoteBean;
import com.jinsilu.freight.ui.dialog.MessageDialog;
import com.jinsilu.freight.ui.fragment.BlankNoteFragment;
import com.jinsilu.freight.ui.fragment.FinishedWaybillFragment;
import com.jinsilu.freight.ui.fragment.UnfinishedWaybillFragment;

import java.util.List;

/**
 * author : byd
 * time   : 2022-04-08
 * desc   : 我的白条
 */
public final class BlankNoteActivity extends MyActivity {

    private TabLayout mTabLayout;
    private ViewPager2 mViewPager;

    private final int activeColor = Color.parseColor("#3265F9");
    private final int normalColor = Color.parseColor("#333333");

    private final int activeSize = 16;
    private final int normalSize = 16;

    private TabLayoutMediator mediator;

    private final String[] tabs = new String[]{"已发放", "已过期"};

    public static final String WHITE_TYPE_OF_TIME_ISSUE_DATE = "0";
    public static final String WHITE_TYPE_OF_EXPIRED = "1";
    public static final String WHITE_TYPE_OF_RECORDS_OF_CONSUMPTION = "2";

    private TextView mTvTotalCredit;
    private TextView mTvAvailableCredit;
    private TextView mTvConsumeDetails;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_blank_note;
    }

    @Override
    protected void initView() {

        mTvTotalCredit = (TextView) findViewById(R.id.tv_total_credit);
        mTvAvailableCredit = (TextView) findViewById(R.id.tv_available_credit);
        mTvConsumeDetails = (TextView) findViewById(R.id.tv_consume_details);

        mTabLayout = findViewById(R.id.tab_layout);
        mViewPager = findViewById(R.id.view_pager);
        //禁用预加载
        mViewPager.setOffscreenPageLimit(ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT);
        //Adapter
        mViewPager.setAdapter(new FragmentStateAdapter(getSupportFragmentManager(), getLifecycle()) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                //FragmentStateAdapter内部自己会管理已实例化的fragment对象。
                // 所以不需要考虑复用的问题
                if (0 == position)
                    return BlankNoteFragment.newInstance(WHITE_TYPE_OF_TIME_ISSUE_DATE);
                else
                    return BlankNoteFragment.newInstance(WHITE_TYPE_OF_EXPIRED);
            }

            @Override
            public int getItemCount() {
                return tabs.length;
            }
        });
        //viewPager 页面切换监听
        mViewPager.registerOnPageChangeCallback(changeCallback);

        mediator = new TabLayoutMediator(mTabLayout, mViewPager, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                //这里可以自定义TabView
                TextView tabView = new TextView(getContext());

                int[][] states = new int[2][];
                states[0] = new int[]{android.R.attr.state_selected};
                states[1] = new int[]{};

                int[] colors = new int[]{activeColor, normalColor};
                ColorStateList colorStateList = new ColorStateList(states, colors);
                tabView.setText(tabs[position]);
                tabView.setTextSize(normalSize);
                tabView.setTextColor(colorStateList);

                tab.setCustomView(tabView);
            }
        });
        //要执行这一句才是真正将两者绑定起来
        mediator.attach();

        setOnClickListener(R.id.tv_consume_details);
    }

    @Override
    protected void initData() {
        getBlankNoteRemain();
        getBlankNoteConsume();
    }

    /**
     * 刷新统计数据
     */
    public void refreshData(){
        getBlankNoteRemain();
        getBlankNoteConsume();
    }

    private void getBlankNoteConsume() {
        // 获取白条消费额度
        EasyHttp.get(this)
                .api(new BlankNoteConsumptionApi())
                .request(new HttpCallback<HttpData<String>>(this) {
                    @Override
                    public void onSucceed(HttpData<String> data) {
                        mTvAvailableCredit.setText(String.format("%s", TextUtils.isEmpty(data.getData()) ? "0.00" : data.getData()));
                    }
                });
    }

    private void getBlankNoteRemain() {
        // 获取白条剩余额度
        EasyHttp.get(this)
                .api(new BlankNoteRemainApi())
                .request(new HttpCallback<HttpData<String>>(this) {
                    @Override
                    public void onSucceed(HttpData<String> data) {
                        mTvTotalCredit.setText(String.format("%s", TextUtils.isEmpty(data.getData()) ? "0.00" : data.getData()));
                    }
                });
    }

    @SingleClick
    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.tv_consume_details) {
            BlankNoteConsumeDetailsActivity.start(this, WHITE_TYPE_OF_RECORDS_OF_CONSUMPTION);
        }
    }

    @SingleClick
    @Override
    public void onRightClick(View v) {
        super.onRightClick(v);
        // 消息对话框
        new MessageDialog.Builder(this)
                // 标题可以不用填写
                .setTitle("使用说明")
                // 内容必须要填写
                .setMessage(R.string.blank_note_instruction)
                // 确定按钮文本
                .setConfirm(getString(R.string.common_confirm))
                // 设置 null 表示不显示取消按钮
                .setCancel(null)
                // 设置点击按钮后不关闭对话框
                //.setAutoDismiss(false)
                .show();
    }

    private final ViewPager2.OnPageChangeCallback changeCallback = new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageSelected(int position) {
            //可以来设置选中时tab的大小
            int tabCount = mTabLayout.getTabCount();
            for (int i = 0; i < tabCount; i++) {
                TabLayout.Tab tab = mTabLayout.getTabAt(i);
                TextView tabView = null;
                if (tab != null) {
                    tabView = (TextView) tab.getCustomView();
                }
                if (tab != null) {
                    if (tab.getPosition() == position) {
                        if (tabView != null) {
                            tabView.setTextSize(activeSize);
                            tabView.setTypeface(Typeface.DEFAULT_BOLD);
                        }
                    } else {
                        if (tabView != null) {
                            tabView.setTextSize(normalSize);
                            tabView.setTypeface(Typeface.DEFAULT);
                        }
                    }
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        if (null != mediator)
            mediator.detach();
        if (null != mViewPager && null != changeCallback)
            mViewPager.unregisterOnPageChangeCallback(changeCallback);
        super.onDestroy();
    }

    @Override
    public boolean isStatusBarEnabled() {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled();
    }

}